package com.fastjrun.share.demo.service.impl;

import com.fastjrun.apiworld.service.common.ServiceException;
import com.fastjrun.apiworld.vo.PageResult;
import com.fastjrun.share.demo.common.CodeMsgConstants;
import com.fastjrun.share.demo.dao.SysUserDao;
import com.fastjrun.share.demo.dto.ChangePwdDTO;
import com.fastjrun.share.demo.dto.UserDTO;
import com.fastjrun.share.demo.dto.UserQueryDTO;
import com.fastjrun.share.demo.entity.SysUser;
import com.fastjrun.share.demo.helper.DTOToEntifyConverter;
import com.fastjrun.share.demo.helper.EntityToVOConverter;
import com.fastjrun.share.demo.mapper.SysUserDynamicSqlSupport;
import com.fastjrun.share.demo.service.BaseDemoService;
import com.fastjrun.share.demo.service.SysUserManagerService;
import com.fastjrun.share.demo.vo.TotalVO;
import com.fastjrun.share.demo.vo.UserVO;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.CountDSLCompleter;
import org.mybatis.dynamic.sql.select.QueryExpressionDSL;
import org.mybatis.dynamic.sql.select.SelectModel;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目的
 *
 * @author cuiyingfeng @Copyright 2021 快嘉. All rights reserved.
 */
@Service("sysUserManagerService")
public class SysUserManagerServiceImpl extends BaseDemoService implements SysUserManagerService {

    @Resource
    SysUserDao sysUserDao;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 条件分页查询用户列表
     */
    @Override
    public PageResult<UserVO> search(UserQueryDTO requestBody) {


        String mobile = requestBody.getMobile();
        String userName = requestBody.getUsername();
        Integer current = requestBody.getCurrent();
        Integer size = requestBody.getSize();

        if (current == null || current == 0) {
            current = PAGE_CURRENT;
        }
        if (size == null || size == 0) {
            size = PAGE_SIZE;
        }

        int offset = (current - 1) * size;


        QueryExpressionDSL<SelectModel>.QueryExpressionWhereBuilder builder = SqlBuilder.select(SysUserDao.selectList)
                .from(SysUserDynamicSqlSupport.sysUser)
                .where()
                .configureStatement(c -> c.setNonRenderingWhereClauseAllowed(true));

        if (mobile != null && !mobile.equals("")) {
            builder.and(SysUserDynamicSqlSupport.mobile, SqlBuilder.isEqualTo(mobile));

        }

        if (userName != null && !userName.equals("")) {
            builder.and(SysUserDynamicSqlSupport.username, SqlBuilder.isLike(userName));
        }

        SelectStatementProvider selectStatement = builder
                .limit(size)
                .offset(offset).
                build().render(RenderingStrategies.MYBATIS3);
        List<UserVO> list = sysUserDao.selectMany(selectStatement).stream().map(EntityToVOConverter::convert).collect(Collectors.toList());


        SelectStatementProvider countStatement = builder
                .build().render(RenderingStrategies.MYBATIS3);

        long total = sysUserDao.count(countStatement);

        return composePageResult(current, size, list, total);
    }

    /**
     * 查询用户信息
     */
    @Override
    public UserVO getById(Long id) {
        UserVO userVO0 = new UserVO();
        SysUser sysUser = sysUserDao.selectByPrimaryKey(id).get();
        return EntityToVOConverter.convert(sysUser);
    }

    /**
     * 新增用户
     */
    @Override
    public void add(UserDTO requestBody) {
        SysUser sysUser = DTOToEntifyConverter.convert(requestBody);
        // 默认用户密码就是用户名
        sysUser.setPassword(requestBody.getUsername());
        Date currentDate = new Date(System.currentTimeMillis());
        sysUser.setCreateDate(currentDate);
        sysUser.setUpdateDate(currentDate);
        sysUser.setIsEnabled(1);
        sysUserDao.insert(sysUser);
    }

    /**
     * 修改用户
     */
    @Override
    public void save(UserDTO requestBody) {
        SysUser sysUser = DTOToEntifyConverter.convert(requestBody);
        Date currentDate = new Date(System.currentTimeMillis());
        sysUser.setUpdateDate(currentDate);
        sysUserDao.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 删除用户信息
     */
    @Override
    public void deleteById(Long id) {
        sysUserDao.deleteByPrimaryKey(id);
    }

    /**
     * 修改新密码
     */
    @Override
    public void password(ChangePwdDTO requestBody) {
        Long userId = requestBody.getUserId();
        String newPassword = requestBody.getNewPassword();
        String repPassword = requestBody.getRepPassword();
        if (!newPassword.equals(repPassword)) {
            throw new ServiceException(
                    CodeMsgConstants.SYSUSERMANAGERSERVICEIMPL_21003,
                    this.serviceMessageSource.getMessage(String.valueOf(
                            CodeMsgConstants.SYSUSERMANAGERSERVICEIMPL_21003), null, null));
        }
        SysUser record = new SysUser();
        record.setId(userId);
        record.setPassword(passwordEncoder.encode(newPassword));
        Date currentDate = new Date(System.currentTimeMillis());
        record.setUpdateDate(currentDate);
        sysUserDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public TotalVO total() {
        TotalVO totalVO = new TotalVO();
        totalVO.setTotal(sysUserDao.count(CountDSLCompleter.allRows()));
        return totalVO;
    }
}
